package com.quick.springbootquicky.utils;

import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    /**
     * @Autowired 与 static组合的一种写法
     */
    private static  StringRedisTemplate stringRedisTemplate;

    /**
     * 在工具类中导入对象，在static方法中使用该对象，可以使用@PostConstruct 引入对象，并用@Component注解交给spring容器管理
     */
    @Autowired
    private   StringRedisTemplate redisTemplate;

    @PostConstruct
    public void init(){
        stringRedisTemplate = redisTemplate;
    }

    /**
     * token保存2小时
     * @param key
     * @param value
     */
    public static void set(String key,String value){
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.set(key,value,2, TimeUnit.HOURS);
    }

    /**
     * 设置存储时间
     * @param key
     * @param value
     * @param time
     * @param timeUnit
     */
    public static void set(String key,String value,Integer time,TimeUnit timeUnit){
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.set(key,value,time, timeUnit);
    }

    /**
     * 返回对应值
     * @param key
     * @return
     */
    public static String get(String key){
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        String value = operations.get(key);
        return value;
    }

    /**
     * 删除key value
     * @param key
     */
    public static void delete(String key){
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(key);
    }

    /**
     * 获取过期时间
     * @param key
     * @return
     */
    public static Long getExpireTime(String key) {
        ValueOperations<String,String> operations = stringRedisTemplate.opsForValue();
        return operations.getOperations().getExpire(key);
    }
}
